package com.dy.spring.boot.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.dy.spring.boot.domian.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author dengyy
 */
@Api(tags = "Sentinel测试")
@RestController
public class SentinelController {

    @ApiOperation("创建用户")
    @PostMapping("/s/users")
    public User create(@RequestBody @Valid User user, HttpServletRequest request) {
        return user;
    }

    @SentinelResource(blockHandler = "blockHandlerForGetUser")
    @GetMapping("/s/users/{id}")
    public User findById(@PathVariable Integer id) {
        throw new RuntimeException("getUserById command failed");

    }

    // blockHandler 函数，原方法调用被限流/降级/系统保护的时候调用
    public User blockHandlerForGetUser(Integer id, BlockException ex) {
        return new User("bbb", id, "上海", "aaa@bbb.com", null);

    }

    /**
     * fallback  方法执行异常
     * blockHandler  针对限流后的处理
     * @param id
     * @return
     */

    @SentinelResource(value = "HelloWorld", blockHandler = "exceptionHandler", fallback = "helloFallback")
    @GetMapping("sentinel")
    public String helloWorld(Integer id) {
        System.out.println("你好，欢迎学习sentinel");
        return "你好，欢迎学习sentinel" + new Date();
    }

    public String helloFallback(Integer id) {
        System.out.println("helloFallback : 你被限流了");
        return "helloFallback : 你被限流了" + id;
    }

    public String exceptionHandler(Integer id, BlockException e) {
        System.out.println("blockHandler : 你被限流了");
        return "blockHandler : 你被限流了";
    }


}
